package cn.huiyunche.driver.service.impl;

import cn.huiyunche.base.service.enums.DWaybillStatusEnum;
import cn.huiyunche.base.service.enums.DWaybillStatusTypeEnum;
import cn.huiyunche.base.service.enums.UserStatusEnum;
import cn.huiyunche.base.service.interfaces.DWaybillService;
import cn.huiyunche.base.service.interfaces.DWaybillStatusHistoryService;
import cn.huiyunche.base.service.interfaces.SendMessageService;
import cn.huiyunche.base.service.interfaces.UserService;
import cn.huiyunche.base.service.mappers.*;
import cn.huiyunche.base.service.mappers.ext.WaybillMapper;
import cn.huiyunche.base.service.model.*;
import cn.huiyunche.base.service.vo.WaybillDeliveryVo;
import cn.huiyunche.driver.service.DNoticeService;
import cn.huiyunche.driver.service.TmsDDeliveryAuditService;
import cn.huiyunche.driver.service.TmsDDeliveryIssueDisposalService;
import cn.huiyunche.driver.service.TmsDDeliveryIssueService;
import cn.huiyunche.driver.service.enums.DeliveryAuditEnum;
import cn.huiyunche.driver.service.form.TmsDDeliveryAuditForm;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by houjianhui on 2017/4/10.
 */

@Service
public class TmsDDeliveryAuditServiceImpl implements TmsDDeliveryAuditService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TmsDDeliveryAuditServiceImpl.class);

    @Autowired
    private TmsDDeliveryAuditMapper tmsDDeliveryAuditMapper;

    @Autowired
    private DWaybillMapper dWaybillMapper;

    @Autowired
    private SUserMapper sUserMapper;

    @Autowired
    private TmsDDeliveryIssueService tmsDDeliveryIssueService;

    @Autowired
    private TmsDDeliveryIssueDisposalService tmsDDeliveryIssueDisposalService;

    @Autowired
    private UserService userService;

    @Autowired
    private DWaybillService dWaybillService;

    @Autowired
    private TmsDDeliveryMapper tmsDDeliveryMapper;

    @Autowired
    private DNoticeService dNoticeService;

    @Autowired
    private SendMessageService sendMessageService;

    @Autowired
    private WaybillMapper waybillMapper;

    @Autowired
    private DWaybillStatusHistoryService dWaybillStatusHistoryService;

    @Autowired
    private SUserStatusMapper sUserStatusMapper;

    @Override
    public Long save(TmsDDeliveryAuditForm form) throws Exception {
        LOGGER.info("TmsDDeliveryAuditServiceImpl.save params form: {}", form);
        if (null == form) {
            LOGGER.info("TmsDDeliveryAuditServiceImpl.save form must not be null");
            throw new IllegalArgumentException("表单数据不能为空");
        }

        // 校验数据
        this.verification(form);

        // 保存审核记录
        TmsDDeliveryAudit audit = new TmsDDeliveryAudit();
        BeanUtils.copyProperties(form, audit);

        try {
            this.tmsDDeliveryAuditMapper.insertSelective(audit);
        } catch (Exception e) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.save error: {}", e);
            throw new IllegalArgumentException("保存审核信息异常");
        }

        // 将最新审核记录ID返回
        form.setAuditId(audit.getId());

        // 查询运单
        DWaybill waybill = dWaybillMapper.selectByPrimaryKey(form.getWaybillId());

        // 更新运单信息
        updateWaybill(waybill, form.getAuditResultId());

        // 保存附件
        saveAttach(waybill, form.getAttachs(), form.getDeliveryId());

        if (DeliveryAuditEnum.PASS.getValue() != form.getAuditResultId()) {
            this.saveIssue(form);
        }

        SUser user = userService.selectByPrimaryKey(waybill.getUserId());

        // 禁用用户
        disableUser(waybill, form.getAuditResultId(), user);

        // 推送消息
        saveNotice(form, waybill);

        // 发送短信
        this.sendMsg(form, waybill, user);

        SUserStatus sUserStatus = new SUserStatus();
        sUserStatus.setUserId(user.getId());
        sUserStatus.setUserStatus(UserStatusEnum.F.getValue());
        sUserStatusMapper.insertSelective(sUserStatus);
        return null;
    }

    @Override
    public void updateWaybillStatus() throws Exception {
        LOGGER.info("TmsDDeliveryAuditServiceImpl.updateWaybillStatus start");
        // 查询所有已交车运单
        List<WaybillDeliveryVo> list = waybillMapper.listWaybillDelivery();
        if (CollectionUtils.isNotEmpty(list)) {
            list.stream().forEach(value -> {
                Date currentDate = new Date();
                Date deliveryDate = value.getGmtCreate();
                long queueTime = value.getQueueTime()*3600*1000;
                Date endTime = getDatetime(deliveryDate.getTime() + queueTime);
                if (endTime.before(currentDate)) {
                    DWaybill waybill = new DWaybill();
                    waybill.setId(value.getId());
                    waybill.setWaybillStatus(DWaybillStatusEnum.COMPLETED.getValue());
                    // 添加运单状态变更日志
                    dWaybillStatusHistoryService.add(value.getId(), DWaybillStatusTypeEnum.PROCESS.getText(), DWaybillStatusEnum.COMPLETED.getText(), DWaybillStatusEnum.DEAL_CAR.getText(), 0L, "system");
                    // 更新运单状态
                    dWaybillMapper.updateByPrimaryKeySelective(waybill);
                }
            });
        }
    }

    private void updateWaybill(DWaybill dWaybill, Long auditResultId) throws Exception {
        try {
            dWaybill.setDeliveryCheckStatus(1);
            if (DeliveryAuditEnum.ISSUE_FORBIDDEN_QUEUE.getValue() == auditResultId) {
                dWaybill.setWaybillStatus(DWaybillStatusEnum.COMPLETED.getValue());
            }
            dWaybillMapper.updateByPrimaryKeySelective(dWaybill);
        } catch (Exception e) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.save update dwaybill error: {}", e);
            throw new IllegalArgumentException("更新订单数据异常");
        }
    }


    private void disableUser(DWaybill dWaybill, Long auditResultId, SUser user) throws Exception {
        if (DeliveryAuditEnum.ISSUE_FORBIDDEN_QUEUE.getValue() == auditResultId) {
            try {
                userService.disableAccount(user.getPhone());
            } catch (Exception e) {
                LOGGER.error("TmsDDeliveryAuditServiceImpl.disableUser error: {}", e);
                throw new IllegalArgumentException("禁用用户异常");
            }
        }
    }

    private void saveNotice(TmsDDeliveryAuditForm form, DWaybill dWaybill) throws Exception {
        String content = "";
        String title = "";
        if (DeliveryAuditEnum.PASS.getValue() == form.getAuditResultId()) {
            content = "您的订单" + dWaybill.getOrderCode() + "已审核通过。";
            title = "审核通过";
        } else if (DeliveryAuditEnum.ISSUE_APPROVE_QUEUE.getValue() == form.getAuditResultId()) {
            content = form.getIssueTypeContent();
            title = "订单异常";
        } else if (DeliveryAuditEnum.ISSUE_FORBIDDEN_QUEUE.getValue() == form.getAuditResultId()) {
            content = form.getIssueTypeContent();
            title = "订单异常";
        }
        DNotice dNotice = new DNotice();
        dNotice.setContent(content);
        dNotice.setType(0);
        dNotice.setTitle(title);
        dNotice.setCreator("系统");
        try {
            dNoticeService.addNotice(dNotice, dWaybill.getUserId());
        } catch (Exception e) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.saveNotice error: {}", e);
            throw new IllegalArgumentException("保存通知消息异常");
        }
    }

    private void saveAttach(DWaybill waybill, String attachs, Long deliverId) throws Exception {
        TmsDDelivery tmsDDelivery = tmsDDeliveryMapper.selectByPrimaryKey(deliverId);
        try {
            dWaybillService.postDeliveryAttachment(tmsDDelivery, waybill, attachs);
        } catch (Exception e) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.saveAttach error: {}", e);
            throw new IllegalArgumentException("保存交车照片异常");
        }
    }

    private void saveIssue(TmsDDeliveryAuditForm form) throws Exception{

        // 保存异常类型
        Long issueId;
        try {
            issueId = this.tmsDDeliveryIssueService.save(form);
        } catch (Exception e) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.saveIssue issue error: {}", e);
            throw new IllegalArgumentException("保存异常类型异常");
        }

        // 将异常类型ID返回
        form.setIssueId(issueId);

        // 保存异常处理办法
        try {
            this.tmsDDeliveryIssueDisposalService.save(form);
        } catch (Exception e) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.saveIssue disposal error: {}", e);
            throw new IllegalArgumentException("保存异常处理办法异常");
        }
    }

    private void sendMsg(TmsDDeliveryAuditForm form, DWaybill dWaybill, SUser user) throws Exception {
        if (DeliveryAuditEnum.PASS.getValue() == form.getAuditResultId()) {
            sendMessageService.sendWaybillAuditPass(dWaybill.getOrderCode(), form.getQueueTime(), user.getPhone());
        } else if (DeliveryAuditEnum.ISSUE_APPROVE_QUEUE.getValue() == form.getAuditResultId()) {
            sendMessageService.sendWaybillAuditPassApprove(dWaybill.getOrderCode(), form.getIssueTypeContent(), form.getQueueTime(), user.getPhone());
        } else if (DeliveryAuditEnum.ISSUE_FORBIDDEN_QUEUE.getValue() == form.getAuditResultId()) {
            sendMessageService.sendWaybillAuditPassForbidden(dWaybill.getOrderCode(), form.getIssueTypeContent(), user.getPhone());
        }
    }

    private void verification(TmsDDeliveryAuditForm form) throws Exception{

        if (null == form.getAuditResultId() || 0 == form.getAuditResultId()) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.mustItem auditResultId must not be null");
            throw new IllegalArgumentException("交车审核记录类型ID不能为空");
        } else if (StringUtils.isBlank(form.getAuditResult())) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.mustItem auditResult must not be null");
            throw new IllegalArgumentException("交车审核记录类型描述不能为空");
        } else if (null == form.getQueueTime()) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.mustItem queueTime must not be null");
            throw new IllegalArgumentException("排队间隔时间不能为空");
        } else if (form.getQueueTime() > 24 || form.getQueueTime() < 1) {
            LOGGER.error("TmsDDeliveryAuditServiceImpl.mustItem queueTime Must be between 12 to 24");
            throw new IllegalArgumentException("排队间隔时间必须在12到24之间");
        }

    }

    private static Date getDatetime(long millTimes) {
        String sdate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(millTimes));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(sdate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }



}
